package org.gaaidou.ptarmigan.springboot.distributed.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.gaaidou.ptarmigan.springboot.distributed.WorkerIdService;
import org.gaaidou.ptarmigan.springboot.distributed.exception.WorkerIdException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class ZkWorkerIdService implements WorkerIdService {
    private static final String WORKER_ID_PATH_PREFIX = "/worker_id";

    private final Integer workId;

    public ZkWorkerIdService(@Autowired CuratorFramework curatorFramework,
                             @Autowired ApplicationContext applicationContext) {
        try {
            String workIdPath = String.format("%s/%s", WORKER_ID_PATH_PREFIX, applicationContext.getId());
            String path = curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(workIdPath);
            workId = Integer.parseInt(path.replace(workIdPath, "")) % 1024;
        } catch (Exception e) {
            throw new WorkerIdException(e);
        }
    }

    public Integer workId() {
        return workId;
    }


}
